<template>
  <div class="component-upload-image">
      <div class="avatar-uploader-box">
      <!-- 预览 -->
      <div
        :key="index"
        class="video-preview"
        v-for="(item, index) in fileList"
        @mouseover.stop="editstate(item,1)"
        @mouseleave="editstate(item,2)"
      >
      <div class="avatar">
          {{decodeURIComponent(item.name.substring(item.name.lastIndexOf('/') + 1), "utf-8")}}
      </div>
        <!-- 显示查看和删除的按钮弹窗 -->
        <!--  && item.isShowPopup-->
        <div
          class="avatar-uploader-popup"
          v-show="item.isShowPopup"
        >
          <i @click="previewVideo(item)" class="el-icon-zoom-in"></i>
          <i @click="handleRemove(index)" class="el-icon-delete"></i>
        </div>
      </div>
      <el-upload
      action=""
      :http-request="httpRequest"
      list-type="picture-card"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-exceed="handleExceed"
      name="file"
      :show-file-list="false"
      :headers="headers"
      :file-list="fileList"
      :class="{hide: this.fileList.length >= this.limit}"
      :on-change="handleChange"
    >
      <i class="el-icon-plus" />
    </el-upload>
      </div>
      <!-- 上传提示 -->
    <div v-if="showTip" slot="tip" class="el-upload__tip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="1000px"
      append-to-body
    >
    <iframe v-if="suffix == 'doc' || suffix == 'docx'" frameborder="0"
        :src="'https://view.officeapps.live.com/op/view.aspx?src='+dialogImageUrl"
        width='100%' height="500px">
    </iframe>
    <iframe v-else-if="suffix == 'pdf'" frameborder="0"
        :src="dialogImageUrl"
        width='100%' height="500px">
    </iframe>
    <div class="txtclass" v-else-if="suffix == 'txt'">{{txt}}</div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import ObsClient from 'huawei-obs';

export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => [
            "txt",
            "pdf",
            "epub",
            "docx",
            "doc",
          ]
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    dir: {
      type: String,
      default: 'pdf'
    },
    videoBaseUrl: {
      // 已上传服务器路径
      type: String,
      required: true,
    },
  },
  data() {
    return {
        txt:'',//txt文档内容
      dialogImageUrl: '',
      dialogVisible: false,
      hideUpload: false,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      suffix:'',
      fileList: [],
      obs: {},
      bucket: process.env.VUE_APP_OBS_BUCKET,
      obsEndpoint: process.env.VUE_APP_OBS_ENDPOINT
    };
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === 'string') {
              item = { name: item, url: item };
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.obs = new ObsClient({
      access_key_id: process.env.VUE_APP_OBS_AK,
      secret_access_key: process.env.VUE_APP_OBS_SK,
      server: `https://${this.obsEndpoint}`,
      level: 'warn'
    });
    this.obs.headBucket({ Bucket: this.bucket }).then(function(result) {
      if (result.CommonMsg.Status === 404) {
        console.log('云存储配置错误，请联系管理员！原因：存储桶不存在！');
      }
    });
  },
  methods: {
      handleChange(file) {
          console.log(file)
      let reader = new FileReader();
      reader.readAsText(file.raw, "UTF-8");// 如果出现乱码，可以更换编码
    },
    // 删除
    handleRemove(file, fileList) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      this.fileList.splice(findex, 1);
      this.$emit('input', this.listToString(this.fileList));
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = '';
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf('video') > -1;
      }

      if (!isImg) {
        this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}视频格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传视频大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 预览
    previewVideo(file) {
    this.txt = '';//解决txt文档乱码的问题
      this.dialogImageUrl = file.name;
      this.suffix = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
      if(this.suffix == 'txt'){
          let xhr = new XMLHttpRequest();
        xhr.open('GET', file.name, false);// 文件路径
        xhr.overrideMimeType("text/html;charset=utf-8");//默认为utf-8
        xhr.send(null);
        this.txt = xhr.responseText;
      }
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = '';
      separator = separator || ',';
      for (const i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    editstate(item,stuts){
        if(stuts == 1){
          item.isShowPopup = true;
        }else{
          item.isShowPopup = false;
        }
        this.$forceUpdate()
    },
    httpRequest(e) {
      this.obs.putObject({
        Bucket: this.bucket,
        Key: this.dir + '/' + e.file.name,
        SourceFile: e.file
      }).then((result) => {
        if (result.CommonMsg.Status === 200) {
          this.fileList.push({ name: e.file.name, url: this.getFilePath(e.file.name) ,isShowPopup:false,videoLink:this.getFilePath(e.file.name)});
          this.$emit('input', this.listToString(this.fileList), this.fileList);
          this.loading.close();
          return e.file;
        }
      });
    },
    getFilePath(fileName) {
      return `https://${this.bucket}.${this.obsEndpoint}/${this.dir}/${encodeURI(fileName)}`;
    }
  }
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
    display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
    transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
}
$width: 200px;
$height: auto;

.avatar-uploader-box {
    position: relative;
    padding-bottom: 20px;
    min-width: 350px;
    .avatar-uploader {
      .el-upload {
        width: $width;
        height: $height;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        &:hover {
          border-color: #409eff;
        }
        .el-loading-spinner {
          width: $width;
          height: $height;
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-top: 0;
          top: 0;
          .el-loading-text {
            margin: 0;
          }
        }
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: $width;
        height: $height;
        line-height: $height;
        text-align: center;
      }
    }
    .video-preview {
      position: relative;
      padding-right: 20px;
      line-height: 40px;
      .avatar {
        width: 100%;
        height: 40px;
        display: block;
        border-radius: 6px;
        margin-bottom: 20px;
      }
      .avatar-uploader-popup {
        position: absolute;
        top: 0;
        left: 0;
        z-index:999;
        width: 100%;
        height: 40px;
        background: rgba($color: #000000, $alpha: 0.5);
        display: flex;
        justify-content: flex-end;
        align-items: center;
        color: #fff;
        font-size: 20px;
        border-radius: 6px;
        i {
          text-align: center;
          padding: 0 5px;
          font-size: 24px;
        }
      }
    }
    .upload-tip {
      position: absolute;
      bottom: 0;
      left: 0;
      font-size: 12px;
      color: #606266;
      max-width: 350px;
      line-height: 20px;
    }
  }
  .txtclass{
      min-height: 500px;
      overflow: auto;
  }
</style>

